Skip to main content

3-19 29. 顺时针打印矩阵

Date:2022-03-19 09:41:59

标签:

  • 按层模拟

题目:29. 顺时针打印矩阵 ( 简单😄 )

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

分析

题解

function spiralOrder(matrix: number[][]): number[] {
if (matrix.length <= 0) return []

const len0 = matrix.length
const len1 = matrix[0].length
let t = 0,
b = len0 - 1,
l = 0,
r = len1 - 1

const res = []

while (true) {
for (let i = l; i <= r; ++i) {
res.push(matrix[t][i])
}
if (++t > b) break

for (let i = t; i <= b; ++i) {
res.push(matrix[i][r])
}
if (--r < l) break

for (let i = r; i >= l; --i) {
res.push(matrix[b][i])
}
if (--b < t) break

for (let i = b; i >= t; --i) {
res.push(matrix[i][l])
}
if (++l > r) break
}

return res
}

使用

function main() {
// const matrix = [
// [1, 2, 3],
// [4, 5, 6],
// [7, 8, 9],
// ]
const matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]

console.log('[]:', spiralOrder(matrix))
}

main()

export {}